var manifestId;
$(function () {
	manifestId = $.getUrlParam("id");
	
	//站点的下拉列表，显示本公司下的站点列表
	$.ajax({
	    url: "../station/getStationByComnum.htm",
	    cache: false,
	    type: "get",
	    dataType: "json",
	    async: false,
	    success: function (result) {
	        if (result.status == 0) {
	            var data = result.data;
	            addOptions(data, "#manifestStartCity");	//初始化起点下拉框
	            addOptions(data, "#manifestEndCity");	//初始化终点下拉框
	        } 
	    }
	});
	
	//初始化车牌号自动补全插件
	initTruckTypeAhead("#truckCarNum", "../manifest/getTruckNumAndCarNum.htm");
	
    //是否验证成功
    $('#editManifestForm').validationEngine('attach', {
        validationEventTrigger : '',	//设置提交的时候再进行验证
        promptPosition: 'topRight',
        scroll: false,	//屏幕自动滚动到第一个验证不通过的位置。
        focusFirstField : true,	//验证未通过时，是否给第一个不通过的控件获取焦点。
        onValidationComplete : function (form, valid) {
            if (valid){
                if (manifestId == 'null') {
                	addManifestInfo();
                } else {
                	modifyManifestInfo();
                }
            }
        }
    });
    
    //如果company为null，则是增加操作，否则是编辑操作.
    //这个地方使用的return，后面的语句将执行不到
    if(manifestId == 'null'){
    	return;
    }else{
    	echoManifestInfo();
    }
});

//点击编辑回显数据
function echoManifestInfo(){
    $.ajax({
        url: "../manifest/getManifestInfoById.htm",
        cache: false,
        async : false,
        type: "post",
        dataType: "json",
	    data: {manifestId: manifestId},
        success: function (result) {
            if (result.status == 0) {
                var data = result.data;
                $("#editManifestForm").formatForm(data);
                return;
            }
        }
    });
}

//关闭窗口
function closeForm() {
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.layer.close(index);
}

//修改货单信息
function modifyManifestInfo(){
	var validPass = checkCarNum();
	$.ajax({
        url: "../manifest/modifyManifestInfo.htm",
        cache: false,
        type: "post",
        dataType: "json",
        data : $("#editManifestForm").serialize(),
        beforeSend:function(){var index = layer.load(1, { shade: [0.8,'#ddd']});},
        complete:function(){var index = layer.closeAll("loading");},
        success: function (result) {
            if (result.status == 0) {
                parent.layer.msg(result.message, {icon: 1});
                parent.$table.bootstrapTable('refresh', {url: '../manifest/getManifestByPage.htm'});
            } else {
                parent.layer.msg(result.message, {icon: 2});
            }
            closeForm();
        }
    });
}

//增加货单信息
function addManifestInfo() {
	var validPass =  checkCarNum();
	$.ajax({
        url: "../manifest/addToManifestInfo.htm",
        cache: false,
        type: "post",
        dataType: "json",
        data: $("#editManifestForm").serialize(),
        beforeSend:function(){var index = layer.load(1, { shade: [0.8,'#ddd']});},
        complete:function(){var index = layer.closeAll("loading");},
        success: function (result) {
            if (result.status == 0) {
                parent.layer.msg(result.message, {icon: 1});
                parent.$table.bootstrapTable('refresh', {url: '../manifest/getManifestByPage.htm'});
                closeForm();
            } else {
                parent.layer.msg(result.message, {icon: 2});
                closeForm();
            }
        }
    });
}

//车牌号自动补全
function initTruckTypeAhead(truckInput, URL){
	$(truckInput).typeahead({
		source: function(query, process){	//query是输入框输入的文本内容, process是一个回调函数
			 $.ajax({
		        url: URL,
		        cache: false,
		        type: "post",
		        dataType: "json",
		        data : {carNum: query},
		        success: function (result) {
		          var resultList = result.data.map(function (item) {
	                  var aItem = {
	                				trucknum: item.truckNum, 
	                				carnum: item.truckCarNum,
	                			   };
	                  return JSON.stringify(aItem);
	              });
		           return process(resultList);
		        }
		    });
		},
		minLength:2,	//键入字数多少开始补全
		fitToElement: true,	//选项框宽度与输入框一致
		items: "all",  //最多显示个数
		delay: 300,		//延迟时间
		updater: function (item) {	//这里一定要return，否则选中不显示，外加调用display的时候null reference错误。
			var obj = JSON.parse(item);
			$("#manifestTruck").val(obj.trucknum);
    		return obj.carnum;
		},
        highlighter: function (obj) {	//必须使用highlighter 进行输入框的内容格式化
            var item = JSON.parse(obj);
            var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
            return item.carnum.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                return '<strong>' + match + '</strong>'
            });
        }
    });
}

//检测输入的车牌号是否合法，防止没有在搜索下拉框中选择车牌号
function checkCarNum(){
	var strExp = new RegExp(/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[a-zA-Z]{1}[a-zA-Z0-9]{5}$/);
	var carNum = $("#truckCarNum").val();
	var manifestTruck = $.trim($("#manifestTruck").val());
	if(strExp.test(carNum)){
		if(manifestTruck == '' || typeof(manifestTruck) == "undefined" || manifestTruck ==0){
			parent.layer.msg("请在输入框中选择车牌号!", {icon: 2});
			return false;
		}else{
			return true;
		}
	}else{
		parent.layer.msg("请输入正确的车牌号!", {icon: 2});
		return false;
	}
}

//站点下拉列表  追加到option中
function addOptions(data,selectId){
	for(var i=0;i<data.length;i++){
		$(selectId).append('<option value="' + data[i].stationNum +'">' + data[i].stationName + '</option>');
	}
}